from PySide6.QtWidgets import QMainWindow, QListWidgetItem

from global_variables import GlobalVariables


class DataListPage(QMainWindow):
    def __init__(self, app):
        super().__init__()
        self.app = app
        self.ui = app.ui
        self.__data_list_fill_data__ = self.app.data_list_fill_data

        self.init()

    def init(self):
        self.ui.data_page_limit.currentIndexChanged.connect(self.data_page_limit_current_index_changed)
        self.ui.page_next.clicked.connect(self.page_next_clicked)
        self.ui.page_prev.clicked.connect(self.page_prev_clicked)

    def page_prev_clicked(self):
        GlobalVariables.DATA_LIST_PAGE_NUM -= 1
        self.data_page_limit_current_index_changed()

    def page_next_clicked(self):
        GlobalVariables.DATA_LIST_PAGE_NUM += 1
        self.data_page_limit_current_index_changed()

    def data_page_limit_current_index_changed(self):
        table_name = self.get_table_name()
        if table_name is None:
            return
        page_num = GlobalVariables.DATA_LIST_PAGE_NUM
        limit = int(self.ui.data_page_limit.currentText())
        self.__data_list_fill_data__.data_list_fill_data(table_name=table_name, limit=limit, page_num=page_num)

    def get_table_name(self):
        item = self.ui.table_list.currentItem()
        if isinstance(item, QListWidgetItem):
            return item.text()
        return None
